"use client"

import { useState, useMemo } from 'react'

interface Course {
  lesson_number: string
  course_name: string
  target_char: string
}

interface CourseSidebarProps {
  collapsed: boolean
  onToggle: () => void
  courseList: Course[]
  currentCourseNumber: string
  onSelectCourse: (courseNumber: string) => void
}

// 模拟学习历史数据
interface LearningHistory {
  character: string
  firstLearnedAt: number
  appearedTimes: number
  relatedLessons: number[]
  isNew: boolean
}

// 模拟字根、部首、笔画的学习历史
const getLearningHistory = (targetChar: string, currentLesson: number): {
  radicals: LearningHistory[]
  strokes: LearningHistory[]
  components: LearningHistory[]
} => {
  // 这里应该从实际的学习数据库获取，现在用模拟数据
  const mockData = {
    '木': {
      radicals: [
        { character: '木', firstLearnedAt: 1, appearedTimes: 15, relatedLessons: [1, 4, 8, 12], isNew: currentLesson === 1 }
      ],
      strokes: [
        { character: '一', firstLearnedAt: 1, appearedTimes: 50, relatedLessons: [1, 2, 3], isNew: false },
        { character: '丨', firstLearnedAt: 1, appearedTimes: 45, relatedLessons: [1, 2, 4], isNew: false },
        { character: '丿', firstLearnedAt: 1, appearedTimes: 30, relatedLessons: [1, 3, 5], isNew: false },
        { character: '丶', firstLearnedAt: 1, appearedTimes: 40, relatedLessons: [1, 2, 6], isNew: false }
      ],
      components: [
        { character: '木', firstLearnedAt: 1, appearedTimes: 15, relatedLessons: [1, 4, 8], isNew: currentLesson === 1 }
      ]
    },
    '人': {
      radicals: [
        { character: '人', firstLearnedAt: 2, appearedTimes: 20, relatedLessons: [2, 5, 9], isNew: currentLesson === 2 }
      ],
      strokes: [
        { character: '丿', firstLearnedAt: 1, appearedTimes: 31, relatedLessons: [1, 2, 3], isNew: false },
        { character: '乀', firstLearnedAt: 2, appearedTimes: 25, relatedLessons: [2, 4, 7], isNew: currentLesson === 2 }
      ],
      components: [
        { character: '人', firstLearnedAt: 2, appearedTimes: 20, relatedLessons: [2, 5, 9], isNew: currentLesson === 2 }
      ]
    }
  }
  
  return mockData[targetChar as keyof typeof mockData] || {
    radicals: [],
    strokes: [],
    components: []
  }
}

export function CourseSidebar({
  collapsed,
  onToggle,
  courseList,
  currentCourseNumber,
  onSelectCourse
}: CourseSidebarProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [jumpToLesson, setJumpToLesson] = useState('')
  
  // 获取当前课程信息
  const currentCourse = courseList.find(course => course.lesson_number === currentCourseNumber)
  const currentLessonNum = parseInt(currentCourseNumber)
  
  // 获取学习历史
  const learningHistory = useMemo(() => {
    if (currentCourse) {
      return getLearningHistory(currentCourse.target_char, currentLessonNum)
    }
    return { radicals: [], strokes: [], components: [] }
  }, [currentCourse, currentLessonNum])
  
  // 过滤课程列表
  const filteredCourses = useMemo(() => {
    if (!searchTerm) return courseList
    return courseList.filter(course => 
      course.lesson_number.includes(searchTerm) ||
      course.course_name.includes(searchTerm) ||
      course.target_char.includes(searchTerm)
    )
  }, [courseList, searchTerm])
  
  // 快速跳转
  const handleQuickJump = () => {
    const lessonNum = parseInt(jumpToLesson)
    if (lessonNum >= 1 && lessonNum <= 380) {
      onSelectCourse(lessonNum.toString())
      setJumpToLesson('')
    }
  }
  
  return (
    <div className={`${collapsed ? 'w-20' : 'w-72'} bg-white/95 backdrop-blur-sm flex flex-col transition-all duration-300 shadow-2xl rounded-r-[30px] overflow-hidden h-screen relative`}>
      {/* 装饰性背景 */}
      <div className="absolute top-0 left-0 w-full h-full bg-gradient-to-br from-purple-100/30 to-transparent pointer-events-none"></div>
      
      {/* 头部 */}
      <div className="bg-gradient-to-r from-purple-500 to-purple-600 text-white p-5 flex items-center justify-between min-h-[80px] relative overflow-hidden">
        {/* 装饰元素 */}
        <div className="absolute -right-5 top-1/2 transform -translate-y-1/2 text-6xl opacity-10">📚</div>
        
        {!collapsed && (
          <h2 className="text-lg font-bold text-white drop-shadow-md">课程列表</h2>
        )}
        
        <button
          onClick={onToggle}
          className="w-9 h-9 bg-white/30 hover:bg-white/40 rounded-full flex items-center justify-center text-white transition-all duration-300 hover:scale-110 shadow-lg"
        >
          {collapsed ? '▶' : '◀'}
        </button>
      </div>

      {/* 内容区域 - 分为两部分 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {!collapsed && (
          <>
            {/* 上半部分：课程列表 - 占1/3 */}
            <div className="h-1/3 flex flex-col border-b border-purple-200/50">
              <div className="p-4 border-b border-purple-100/50">
                <h3 className="text-sm font-bold text-purple-700 mb-3">📚 课程总表</h3>
                
                {/* 快速跳转 */}
                <div className="flex gap-2 mb-3">
                  <input
                    type="number"
                    placeholder="跳转到第几课"
                    value={jumpToLesson}
                    onChange={(e) => setJumpToLesson(e.target.value)}
                    className="flex-1 px-2 py-1 text-xs border border-purple-200 rounded-lg focus:outline-none focus:border-purple-400"
                    min="1"
                    max="380"
                  />
                  <button
                    onClick={handleQuickJump}
                    className="px-3 py-1 text-xs bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors"
                  >
                    跳转
                  </button>
                </div>
                
                {/* 搜索框 */}
                <input
                  type="text"
                  placeholder="搜索课程..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full px-3 py-2 text-xs border border-purple-200 rounded-lg focus:outline-none focus:border-purple-400"
                />
              </div>
              
              {/* 课程列表 */}
              <div className="flex-1 overflow-y-auto p-2">
                {filteredCourses.map((course, index) => (
                  <div
                    key={course.lesson_number}
                    onClick={() => onSelectCourse(course.lesson_number)}
                    className={`
                      mb-2 p-2 rounded-lg cursor-pointer transition-all duration-200 text-xs
                      ${currentCourseNumber === course.lesson_number
                        ? 'bg-gradient-to-r from-yellow-400 to-orange-500 text-white shadow-md'
                        : 'bg-gradient-to-r from-pink-300 to-purple-300 text-white hover:shadow-md hover:from-pink-400 hover:to-purple-400'
                      }
                    `}
                  >
                    <div className="font-semibold">第{course.lesson_number}课：{course.target_char}</div>
                  </div>
                ))}
                
                {filteredCourses.length === 0 && (
                  <div className="text-center text-gray-500 text-xs py-4">
                    没有找到匹配的课程
                  </div>
                )}
              </div>
            </div>

            {/* 下半部分：智能教学提醒 - 占2/3 */}
            <div className="h-2/3 p-4 overflow-y-auto">
              <h3 className="text-sm font-bold text-purple-700 mb-3">🧠 智能教学提醒</h3>
              
              {currentCourse && (
                <div className="space-y-3">
                  {/* 部首偏旁学习历史 */}
                  {learningHistory.radicals.length > 0 && (
                    <div className="bg-green-50 border-l-4 border-green-400 p-3 rounded-r-lg">
                      <div className="text-xs font-semibold text-green-800 mb-2">🌱 部首偏旁学习历史</div>
                      {learningHistory.radicals.map((radical, idx) => (
                        <div key={idx} className="text-xs text-green-700 mb-1">
                          <span className="font-bold">{radical.character}</span>
                          {radical.isNew ? (
                            <span className="ml-2 px-1 bg-red-200 text-red-800 rounded">新学</span>
                          ) : (
                            <span className="ml-2 text-green-600">
                              第{radical.firstLearnedAt}课首次学习，已出现{radical.appearedTimes}次
                            </span>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                  
                  {/* 笔画学习历史 */}
                  {learningHistory.strokes.length > 0 && (
                    <div className="bg-indigo-50 border-l-4 border-indigo-400 p-3 rounded-r-lg">
                      <div className="text-xs font-semibold text-indigo-800 mb-2">✏️ 笔画学习历史</div>
                      {learningHistory.strokes.map((stroke, idx) => (
                        <div key={idx} className="text-xs text-indigo-700 mb-1">
                          <span className="font-bold">{stroke.character}</span>
                          {stroke.isNew ? (
                            <span className="ml-2 px-1 bg-red-200 text-red-800 rounded">新学</span>
                          ) : (
                            <span className="ml-2 text-indigo-600">
                              第{stroke.firstLearnedAt}课首次学习，已出现{stroke.appearedTimes}次
                            </span>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                  
                  {/* 高频字根提醒 */}
                  <div className="bg-orange-50 border-l-4 border-orange-400 p-3 rounded-r-lg">
                    <div className="text-xs font-semibold text-orange-800 mb-2">🔥 高频字根提醒</div>
                    <div className="text-xs text-orange-700 space-y-1">
                      <div>• <span className="font-bold">木</span> - 组词造句高频字，常用于：树木、木头、木材</div>
                      <div>• <span className="font-bold">一</span> - 基础笔画，出现频率极高</div>
                      <div>• <span className="font-bold">丨</span> - 基础笔画，构字常用</div>
                    </div>
                  </div>
                  
                  {/* 复习建议 */}
                  <div className="bg-purple-50 border-l-4 border-purple-400 p-3 rounded-r-lg">
                    <div className="text-xs font-semibold text-purple-800 mb-2">📚 复习建议</div>
                    <div className="text-xs text-purple-700 space-y-1">
                      <div>• 重点复习：第{learningHistory.radicals[0]?.firstLearnedAt || 1}课的基础字根</div>
                      <div>• 关联课程：第{learningHistory.radicals[0]?.relatedLessons.slice(0, 2).join('、') || '4、8'}课</div>
                      <div>• 本课新内容：{learningHistory.radicals.filter(r => r.isNew).length}个新字根</div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </>
        )}
        
        {collapsed && (
          <div className="flex-1 p-4 overflow-y-auto">
            {courseList.slice(0, 5).map((course, index) => (
              <div
                key={course.lesson_number}
                onClick={() => onSelectCourse(course.lesson_number)}
                className={`
                  mb-3 p-3 rounded-xl cursor-pointer transition-all duration-300 text-center
                  ${currentCourseNumber === course.lesson_number
                    ? 'bg-gradient-to-r from-yellow-400 to-orange-500 text-white shadow-lg'
                    : 'bg-gradient-to-r from-pink-400 to-purple-500 text-white hover:shadow-lg'
                  }
                `}
              >
                <div className="text-xs font-bold">{course.lesson_number}</div>
              </div>
            ))}
          </div>
        )}
      </div>


    </div>
  )
} 